package com.nosnow.ucenter.controller;

import com.nosnow.common.utils.JwtUtils;
import com.nosnow.common.utils.R;
import com.nosnow.common.vo.UcenterMemberOrder;
import com.nosnow.ucenter.entity.UcenterMember;
import com.nosnow.ucenter.entity.vo.LoginVo;
import com.nosnow.ucenter.entity.vo.RegisterVo;
import com.nosnow.ucenter.service.UcenterMemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author bingheng
 * @since 2020-04-26
 */
@RestController
@RequestMapping("/ucenter")
public class UcenterMemberController {

    @Autowired
    private UcenterMemberService ucenterMemberService;

    /**
     * 用户登录
     * @param loginVo
     * @return
     */
    @PostMapping("loginUser")
    public R loginUser(@RequestBody LoginVo loginVo) {
        String token = ucenterMemberService.login(loginVo);
        return R.ok().data("token", token);
    }

    /**
     * 新用户注册
     * @param registerVo
     * @return
     */
    @PostMapping("registerUser")
    public R registerUser(@RequestBody RegisterVo registerVo) {
        ucenterMemberService.register(registerVo);
        return R.ok();
    }

    /**
     * 根据token获取用户信息
     * @param request
     * @return
     */
    @GetMapping("getMemberInfo")
    public R getMemberInfo(HttpServletRequest request) {
        // 1. 调用Jwt工具类中的方法，根据request对象获取头信息，返回用户Id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);

        // 2. 根据用户Id，查询用户信息
        UcenterMember ucenterMember = ucenterMemberService.getById(memberId);
        return R.ok().data("userInfo", ucenterMember);
    }

    /**
     * 根据用户Id获取用户信息
     */
    @PostMapping("getUserInfoOrder/{id}")
    public UcenterMemberOrder getUserInfoOrder(@PathVariable String id) {
        UcenterMember ucenterMember = ucenterMemberService.getById(id);
        UcenterMemberOrder ucenterMemberOrder = new UcenterMemberOrder();
        BeanUtils.copyProperties(ucenterMember, ucenterMemberOrder);
        return ucenterMemberOrder;
    }

    // 查询某一天注册人数
    @GetMapping("countRegister/{day}")
    public R countRegister(@PathVariable String day) {
        Integer count = ucenterMemberService.countRegisterDay(day);
        return R.ok().data("countRegister", count);
    }

}

